<template>
  <div class="search-container">
    <!-- 搜索栏 -->
        <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form class="search-form" action="/">
        <van-search
            class="serch"
            v-model="SearchText"
            show-action
            placeholder="请输入搜索关键词"
            background="#3296fa"
            @search="onSearch"
            @cancel="onCancel"
            @focus="isResultShow = false"
        />
    </form>    
    <!-- /搜索栏 -->

    <!-- 搜索结果 -->
    <search-result 
        v-if='isResultShow'
        :searchText="SearchText" 
    />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion 
        v-else-if="SearchText" 
        :searchText="SearchText" 
        @search="onSearch" 
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history 
        v-else 
        :search-histories="searchHistories" 
        @delete-searchHistories = 'deleteFn'
        @clear-search-historises = 'searchHistories = []'
        @search = 'onSearch'
     ></search-history>
    <!-- /搜索历史记录 -->

  </div>

</template>

<script>
import SearchHistory from './components/search-history.vue';
import SearchSuggestion from './components/search-suggestion.vue';
import SearchResult from './components/search-result.vue';
import { setItem, getItem } from '@/utils/storage'

export default {
    name: 'SearchIndex',
    components: {
        SearchHistory,
        SearchSuggestion,
        SearchResult
    },
    data() {
        return {
            SearchText: '',
            isResultShow:false , //控制搜索结果的展示
            searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || []  // 搜索的历史记录数据
        };
    },
    watch: {
        searchHistories(value) {
            setItem("TOUTIAO_SEARCH_HISTORIES",value)
        }
    },
    methods: {
        onSearch(val) {
            // 更新文本框内容
            this.SearchText = val    

            // 存储搜索历史记录
            // 要求：不要有重复的历史记录，最新的排在最前面 
            const index = this.searchHistories.indexOf(val)
            if (index != -1) {
                this.searchHistories.splice(index,1)
            }
            this.searchHistories.unshift(val)
            
            // 显示搜索结果
            this.isResultShow = true
        },
        onCancel () {
            // 取消按钮，返回首页
            this.$router.back()
        },
        deleteFn(index) {
            this.searchHistories.splice(index, 1)
        }
    }
}
</script>

<style scoped lang="less">
.search-container{
    padding-top: 108px;
    .search-form{
        position: fixed;
        top: 0;
        left: 0;  
        right: 0;
        z-index: 1;
    }
    .serch{
        .van-search__action{
            font-size: 28px;
            letter-spacing: 1px;
            color: #ffffff;
        }
    }
}
</style>